import { inject, reactive, computed } from "vue";

const piniaSymbol = Symbol("pinia");
export function createPinia() {
  const stores = new Map();
  const pinia = {
    install(app) {
      console.log("install pinia状态管理库");
      app.provide(piniaSymbol, this);
      // 添加全局属性以便模板中使用
      app.config.globalProperties.$pinia = pinia;
    },
    _stores: stores
  };
  return pinia;
}


export function defineStore(id, options) {
  console.log("defineStore", id, options);
  return function useStore() {
    const pinia = inject(piniaSymbol);
    console.log("useStore", pinia);
    console.log(pinia._stores)

    if (!pinia) {
      throw new Error("pinia未安装");
    }

    if (pinia._stores.has(id)) {
      return pinia._stores.get(id);
    }

    try {


      console.log("创建一个新的状态管理器");

      const state = reactive(options.state());
      console.log("state", state);
      // 一次性创建完整的 store 上下文
      const storeContext = { state };
      const actions = {}
      for (let key in options.actions) {
        actions[key] = (...args) => {
          return options.actions[key].call(storeContext, ...args);
        }
      }

      // 将 actions 添加到上下文，支持 actions 间调用
      Object.assign(storeContext, actions);

      const getters = {}
      for (const key in options.getters) {
        getters[key] = computed(() => {
          // 支持两种调用方式
          if (options.getters[key].length === 1) {
            return options.getters[key](state);
          } else {
            return options.getters[key].call(storeContext);
          }
        })
      }
      const store = { ...state, ...actions, ...getters };
      pinia._stores.set(id, store);
      console.log("stores", pinia._stores);
      return store;
    } catch (error) {
      console.log(error)
    }
  }
}